package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.annotation.Log;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author atguigu-mqx
 * @ClassName AccountReceiver
 * @description: TODO
 * @date 2024年09月10日
 * @version: 1.0
 */
@Component
@Slf4j
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    //  如何保证消息不丢失?  发送者： 消息持久化： 开启消息确认机制：消息是否到交换机，队列;  消费者：ack或nack; 消息异常信息表
    //  监听账户初始化信息

    /**
     *  监听账户初始化信息
     * @param userId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER ,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void initAccount(Long userId, Message message, Channel channel){
        try {
            //  先判断当前用户Id 是否为空
            if (null != userId){
                //  调用服务层方法，初始化账户金额
                userAccountService.initAccount(userId);
            }
        } catch (Exception e) {
            log.error("消息消费异常用户Id {}",userId);
            //  先重回3次， channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //  到了3次，之后依然消费失败：调用数据库异常消息表的mapper msgMapper.insert();
        }
        //  手动确认消息，只有确认之后，消息才会从队列中删除.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
